package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.People;
import com.example.entity.Result;
import com.example.service.PeopleService;
import com.example.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/people")
public class PeopleController {

    @Autowired
    PeopleService peopleService;

    @GetMapping("/selectAll")
    public Result selectAll() {
        JSONObject jsonObject = peopleService.selectAll();
        String msg = (String)jsonObject.get("msg");
        if (msg.equals("success")) {
            List<People> peopleNodeList = (List<People>)jsonObject.get("data");
            return ResultUtil.success(peopleNodeList);
        }
        return ResultUtil.error(500, msg);
    }

    @GetMapping("/selectById")
    public Result selectById(Long id) {
        People peopleNode = peopleService.selectById(id);
        return ResultUtil.success(peopleNode);
    }

    @PostMapping("/deleteById")
    public Result deleteById(@RequestBody People people) {
        Boolean flag = peopleService.deleteById(people.getId());
        if (flag == true) {
            return ResultUtil.success(people);
        }
        return ResultUtil.error(500,"删除失败，因为还有关联关系");
    }

    @PostMapping("/update")
    public Result update(@RequestBody People people) {
        JSONObject jsonObject = peopleService.update(people);
        String msg = (String) jsonObject.get("msg");
        if (msg.equals("success")) {
            People peopleNode = (People)jsonObject.get("data");
            return ResultUtil.success(peopleNode);
        }
        return ResultUtil.error(500, msg);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody People people) {
        JSONObject jsonObject = peopleService.insert(people);
        String msg = (String) jsonObject.get("msg");
        if (msg.equals("success")) {
            People peopleNode = (People)jsonObject.get("data");
            return ResultUtil.success(peopleNode);
        }
        return ResultUtil.error(500, msg);
    }
}
